<template>
  <div class="my-posts">
    <!-- 筛选工具栏 -->
    <div
      class="filter-toolbar bg-white dark:bg-gray-800 p-4 rounded-lg shadow-sm mb-6"
    >
      <div class="flex flex-wrap gap-4">
        <!-- 排序选项 -->
        <el-radio-group v-model="sortBy" @change="handleSortChange">
          <el-radio-button label="newest">最新发布</el-radio-button>
          <el-radio-button label="most_liked">最多点赞</el-radio-button>
          <el-radio-button label="most_commented">最多评论</el-radio-button>
        </el-radio-group>

        <!-- 内容类型 -->
        <el-select
          v-model="contentType"
          placeholder="内容类型"
          clearable
          @change="handleContentTypeChange"
        >
          <el-option
            v-for="type in contentTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>

        <!-- 搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索动态内容"
          class="w-64"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <!-- 批量操作 -->
        <div class="flex-1 flex justify-end gap-4">
          <el-button type="primary" @click="handleCreate"> 发布动态 </el-button>
          <el-button
            type="danger"
            :disabled="!selectedItems.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 动态列表 -->
    <div class="posts-list dark:bg-gray-800" v-loading="loading">
      <el-table
        v-model:selected="selectedItems"
        :data="postsList"
        style="width: 100%"
        class="!bg-transparent"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="内容" min-width="300">
          <template #default="{ row }">
            <div class="flex items-start gap-4">
              <!-- 缩略图 -->
              <div v-if="row.media?.length" class="flex-shrink-0">
                <el-image
                  :src="row.media[0]"
                  class="w-20 h-20 rounded-lg object-cover"
                  :preview-src-list="row.media"
                />
              </div>

              <!-- 文本内容 -->
              <div class="flex-1 min-w-0">
                <div class="text-sm line-clamp-2 dark:text-gray-200">
                  {{ row.content }}
                </div>
                <div
                  class="mt-2 flex items-center text-xs text-gray-500 dark:text-gray-400 gap-2"
                >
                  <span>{{ formatTime(row.createTime) }}</span>
                  <el-tag v-if="row.visibility !== 'public'" size="small">
                    {{ visibilityLabels[row.visibility] }}
                  </el-tag>
                  <el-tag
                    v-for="topic in row.topics"
                    :key="topic.id"
                    size="small"
                    class="cursor-pointer"
                    @click="handleTopicClick(topic)"
                  >
                    #{{ topic.name }}
                  </el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="互动数据" width="200">
          <template #default="{ row }">
            <div class="flex items-center gap-4">
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span>{{ row.likes }}</span>
              </div>
              <div class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                <span>{{ row.comments }}</span>
              </div>
              <div class="stat-item">
                <el-icon><Share /></el-icon>
                <span>{{ row.shares }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleView(row)">
                查看
              </el-button>
              <el-button type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-wrapper flex justify-center mt-8">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && !postsList.length" description="暂无动态内容">
        <el-button type="primary" @click="handleCreate">
          发布第一条动态
        </el-button>
      </el-empty>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      :title="editingPost ? '编辑动态' : '发布动态'"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <PostForm
        :hot-topics="hotTopics"
        :initial-data="editingPost"
        @cancel="showEditDialog = false"
        @submit="handlePostSubmit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Star, ChatDotRound, Share } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import PostForm from "./PostForm.vue";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();

// 列表数据
const postsList = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const sortBy = ref("newest");
const contentType = ref("");
const searchQuery = ref("");
const selectedItems = ref([]);

// 内容类型选项
const contentTypes = [
  { label: "全部", value: "" },
  { label: "图文", value: "image" },
  { label: "视频", value: "video" },
  { label: "攻略", value: "guide" },
  { label: "问答", value: "qa" },
];

// 可见性标签
const visibilityLabels = {
  public: "所有人可见",
  friends: "仅好友可见",
  private: "仅自己可见",
};

// 热门话题
const hotTopics = ref([
  {
    id: 1,
    name: "贵港美食探店",
    count: 1234,
  },
  {
    id: 2,
    name: "文化之旅",
    count: 890,
  },
]);

// 编辑相关
const showEditDialog = ref(false);
const editingPost = ref(null);

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 获取动态列表
const getPostsList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取动态列表API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          items: [
            {
              id: 1,
              content: "这是一条动态内容...",
              media: ["/images/posts/example.jpg"],
              topics: [{ id: 1, name: "贵港美食探店" }],
              createTime: "2024-03-15 10:00:00",
              visibility: "public",
              likes: 123,
              comments: 45,
              shares: 67,
            },
          ],
          total: 100,
        });
      }, 500);
    });

    postsList.value = response.items;
    total.value = response.total;
  } catch (error) {
    console.error("获取动态列表失败:", error);
    ElMessage.error("获取动态列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理内容类型变化
const handleContentTypeChange = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getPostsList();
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

// 处理话题点击
const handleTopicClick = (topic) => {
  router.push(`/community/topic/${topic.id}`);
};

// 处理查看
const handleView = (item) => {
  router.push(`/community/post/${item.id}`);
};

// 处理创建
const handleCreate = () => {
  editingPost.value = null;
  showEditDialog.value = true;
};

// 处理编辑
const handleEdit = (item) => {
  editingPost.value = { ...item };
  showEditDialog.value = true;
};

// 处理删除
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这条动态吗？删除后将无法恢复。",
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // TODO: 调用删除动态API
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success("删除成功");
    getPostsList();
  } catch {
    // 用户取消操作
  }
};

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.value.length} 条动态吗？删除后将无法恢复。`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // TODO: 调用批量删除API
    await new Promise((resolve) => setTimeout(resolve, 500));

    ElMessage.success("删除成功");
    getPostsList();
  } catch {
    // 用户取消操作
  }
};

// 处理动态提交
const handlePostSubmit = async (postData) => {
  try {
    // TODO: 调用创建/更新动态API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    ElMessage.success(editingPost.value ? "更新成功" : "发布成功");
    showEditDialog.value = false;
    getPostsList();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getPostsList();
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getPostsList();
};

// 页面加载时获取数据
onMounted(() => {
  getPostsList();
});
</script>

<style lang="scss" scoped>
.my-posts {
  .filter-toolbar {
    :deep(.el-radio-group) {
      @apply flex flex-wrap gap-2;
    }
  }

  .posts-list {
    :deep(.el-table) {
      @apply rounded-lg overflow-hidden;
    }

    .stat-item {
      @apply flex items-center gap-1 text-gray-500;
    }
  }

  .el-table {
    --el-table-bg-color: transparent;
    --el-table-tr-bg-color: transparent;
    --el-table-header-bg-color: transparent;
    --el-table-border-color: var(--el-border-color);

    :deep(.el-table__cell) {
      background: transparent;
    }
  }

  :deep(.dark) {
    .el-table {
      --el-table-text-color: var(--el-text-color-primary);
      --el-table-header-text-color: var(--el-text-color-regular);
      --el-table-border-color: var(--el-border-color-darker);
    }

    .el-input__wrapper {
      background-color: var(--el-bg-color);
    }

    .el-button--primary {
      --el-button-hover-bg-color: var(--el-color-primary-light-3);
      --el-button-hover-border-color: var(--el-color-primary-light-3);
    }

    .el-dialog {
      background: var(--el-bg-color);

      .el-dialog__header {
        color: var(--el-text-color-primary);
      }
    }

    .el-empty {
      --el-empty-description-color: var(--el-text-color-secondary);
    }
  }
}
</style>
